#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "common_gestor_envios.h"


using std::size_t;
using std::string;
using std::cout;
using std::endl;

Gestor_envios::Gestor_envios() {
}

Gestor_envios::~Gestor_envios() {
}

bool Gestor_envios::buscar_fin_de_linea(char* buffer) {
    if (strstr(buffer, "\n") != NULL) {
        return true;
    }
    return false;
}

int Gestor_envios::agrandar_buffer(char* buffer, int buffer_tam) {
    int tam = strlen(buffer) * 2; //
    char* aux = (char*) malloc(tam * sizeof (char));
    strncpy(aux, buffer, buffer_tam);
    aux[buffer_tam] = '\0';
    char* aux_buffer = buffer;
    buffer = aux;
    free(aux_buffer);
    return tam;
}

int Gestor_envios::enviar(int aux_fd, string buffer, int tam) {
    unsigned int enviados = 0; //cantidad de bytes ya enviados.    
    int falta_enviar = tam; //cantidad de bytes que faltan enviar.
    int n;
    const char* aux = buffer.c_str();
    while (enviados < buffer.size()) {
        n = send(aux_fd, aux + enviados, falta_enviar, 0);
        if (n == -1) {
            return -1;
        }
        enviados += n;
        falta_enviar -= n;
    }
    return 0;
}

int Gestor_envios::recibir(int aux_fd, string* buffer, int tam) {
    int numbytes;
    int tam_buffer = tam;
    char* aux = (char*) malloc(tam_buffer + 1 * sizeof (char));
    if ((numbytes = recv(aux_fd, aux, tam_buffer, 0)) == -1) {
        free(aux);
        return -1;
    }
    aux[numbytes] = '\0';
    *buffer = string(aux);
    free(aux);
    return numbytes;
}
